import React, { useState } from "react";
import { Space, Input, AutoComplete, Button } from "antd";
import { SearchOutlined } from "@ant-design/icons";

const Search = () => {
  const [searchValue, setSearchValue] = useState("");
  const [history, setHistory] = useState([]);

  const handleSearch = () => {
    // 搜索逻辑，将搜索值加入历史记录
    if (searchValue !== "") {
      setHistory([searchValue, ...history]);
      setSearchValue("");
    }
  };

  const handleClearHistory = () => {
    // 清空历史记录
    setHistory([]);
    setSearchValue(""); // 清空输入框的值
  };

  const handleSearchChange = (value) => {
    setSearchValue(value);
  };

  const selectSearchItem = (value) => {
    if (value === "clear") {
      // 点击清空历史记录按钮
      handleClearHistory();
    } else {
      setSearchValue(value);
      handleSearch();
    }
  };

  const options = history.map((item) => ({ value: item }));

  // 添加清空历史记录按钮的选项，只有当历史记录不为空时才显示
  if (history.length > 0) {
    options.push({ value: "clear", label: "清空历史记录" });
  }

  return (
    <Space direction="vertical" style={{ width: 300 }}>
      <AutoComplete
        options={options}
        value={searchValue}
        style={{ width: 300 }}
        onChange={handleSearchChange}
        onSelect={selectSearchItem}
        placeholder={"搜索关键字"}
        backfill={true}
      >
        <Input
          suffix={
            <SearchOutlined
              onClick={handleSearch}
              style={{ cursor: "pointer" }}
            />
          }
          value={searchValue}
          onChange={(e) => setSearchValue(e.target.value)}
        />
      </AutoComplete>
    </Space>
  );
};

export default Search;